<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\batch\kuaishou;

use app\enum\CommonEnum;
use app\model\KsPicModel;
use app\service\batch\MediaInterface;
use app\service\batch\MediaService;
use app\service\client\AccountService;
use app\service\kuaishou\DspService;

class PicPushService extends MediaService implements MediaInterface
{
    protected string $advertiserId;

    protected array $imageTokens = [];

    protected int $pageSize = 100;

    public function pushPic(string $advertiserTd, array $targetAdvertiserIds, array $filter = [])
    {
        if (empty($advertiserTd)) {
            return self::setError('源账户不能为空');
        }
        if (empty($targetAdvertiserIds)) {
            return self::setError('目标账户不能为空');
        }
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserTd);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $this->advertiserId = $advertiserTd;
        $this->_getImageTokens($filter);
        if (count($this->imageTokens) === 0) {
            return self::setError('源账户下没有图片');
        }
        $times = ceil(count($this->imageTokens) / $this->pageSize);
        for ($i = 0; $i < $times; ++$i) {
            $picStart = ($i + 1) * $this->pageSize - $this->pageSize;
            $pics = array_slice($this->imageTokens, $picStart, $this->pageSize);
            $res = $this->_sharePic($token, $pics, $targetAdvertiserIds);
            if (! $res) {
                return false;
            }
            dump($res);
        }
        return true;
    }

    private function _getImageTokens(array $filter = [])
    {
        $where = [['advertiser_id', '=', $this->advertiserId]];
        if (! empty($filter['start_time']) && intval($filter['start_time']) > 0) {
            $where[] = [
                'create_time',
                '>=',
                intval($filter['start_time']),
            ];
        }
        if (! empty($filter['end_time']) && intval($filter['end_time']) > 0) {
            $where[] = [
                'create_time',
                '<=',
                intval($filter['end_time']),
            ];
        }
        $query = (new KsPicModel())->where($where)->field('image_token');
        if (! empty($filter['limit']) && intval($filter['limit']) > 0) {
            $query = $query->limit(intval($filter['limit']))->order('id', 'desc');
        }
        $results = $query->select();
        foreach ($results as $result) {
            if (! empty($result->image_token)) {
                $this->imageTokens[] = $result->image_token;
            }
        }
    }

    private function _sharePic(string $token, array $pics, array $targetAdvertiserIds)
    {
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];

        $params = [
            'advertiser_id' => $this->advertiserId,
            'image_tokens' => $pics,
            'share_advertiser_ids' => $targetAdvertiserIds,
        ];
        return DspService::picShare($headers, $params);
    }
}
